package com.sprouting.personal.filter;

import com.sprouting.personal.service.core.XssHttpServletRequestWrapper;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * XSS过滤器
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2021/12/9 11:06
 */
@WebFilter(urlPatterns = "/*")
public class XssFilter implements Filter {

    /**
     * xss 路径白名单，不进行xss过滤
     */
    @Value("#{'${xss.white.url}'.split(',')}")
    private List<String> xssWhiteUrlList;

    /**
     * 初始化方法
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 过滤器
     * @param servletRequest 请求
     * @param servletResponse 响应
     * @param chain 过滤器链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if (xssWhiteUrlList != null){
            if (xssWhiteUrlList.contains(uri)){
                // 不进行xss过滤
                chain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        // xss过滤器核心
        XssHttpServletRequestWrapper wrapper = new XssHttpServletRequestWrapper(request);
        chain.doFilter(wrapper, servletResponse);
    }

    /**
     * 销毁方法
     */
    @Override
    public void destroy() {

    }
}
